package com.bw.hongye.building.service;

import com.alibaba.fastjson.JSON;
import com.bw.hongye.building.dao.BuildingDao;
import com.bw.hongye.building.entity.BuildingEntity;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class contextServer {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private BuildingDao  buildingDao;

    //1。解析 放入索引库中
    public boolean parseContext() throws Exception{

        List<BuildingEntity> contexts = buildingDao.selectList(null);
        //2.把查询出来的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < contexts.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("t_index").id(""+(i+1)).source(JSON.toJSONString(contexts.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

     //2 .获取这些数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword, int pageNo, int pageSize) throws Exception {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件查询
        SearchRequest jd_goods = new SearchRequest( "t_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //分也
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("buildingName", keyword);
        searchSourceBuilder.query(title);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        jd_goods.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    //3 .获取这些数据实现搜索功能(高亮)
    public List<Map<String,Object>> searchPagehighligh(String keyword,int pageNo,int pageSize) throws Exception {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件查询
        SearchRequest jd_goods = new SearchRequest( "t_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //分也
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("buildingName", keyword);
        searchSourceBuilder.query(title);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("buildingName");
        //一个查询 多个高亮
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        jd_goods.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title1 = highlightFields.get("buildingName");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if(title1!=null){
                Text[] fragments = title1.fragments();
                String n_title="";
                for(Text text:fragments){
                    n_title+="text";
                }
                //替换成高亮的字段
                sourceAsMap.put("buildingName",n_title);
            }
            list.add(hit.getSourceAsMap());
        }
        return list;
    }



    public List<Map<String, Object>> searchPageHighlightBuilder(String keyword, int page, int size) throws Exception {
         /* if(page<=1){
            page = 1;
        }*/
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("t_index");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(page);
        sourceBuilder.size(size);
        if(!"".equals(keyword)){

            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyword, "buildingName");
            sourceBuilder.query(multiMatchQueryBuilder);

            sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("buildingName");

            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            sourceBuilder.highlighter(highlightBuilder);
            //执行搜索
            searchRequest.source(sourceBuilder);
        }
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : search.getHits().getHits()) {

            //解析高亮
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField deconration = highlightFields.get("buildingName");
            HashMap<String,HighlightField> map=new HashMap<>();
            map.put("buildingName",deconration);
            list.add( HighlightFieldsUtils(map,documentFields));
        }
        return list;
    }

    public static  Map<String, Object> HighlightFieldsUtils(HashMap<String,HighlightField> map,SearchHit documentFields){
        Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
        for(String key:map.keySet()){
            if (map.get(key)!=null){
                Text[] fragments = map.get(key).fragments();
                String a = "";
                for (Text text : fragments) {
                    a += text;
                }
                sourceAsMap.put(key,a);
            }
        }
        return sourceAsMap;
    }

}